<?PHP
/*
$basex = new basex;

// Zero pad the number if need be
$basex->min_digits = 5;

// Set the charset to use in your base
$basex->charset = array_merge($basex->charset,$charset = range("0","9"));
$basex->charset = array_merge($basex->charset,$charset = range("a","z"));
#$basex->charset = array_merge($basex->charset,$charset = range("A","Z"));

// Set the base to whatever you want, leaving it blank causes it to use the sizeof(charset)
$basex->base = sizeof($basex->charset);

$rand = rand(0,pow($basex->base,$basex->min_digits));
$enc = $basex->basex_encode($rand);
$dec = $basex->basex_decode($enc);

print "Using base: {$basex->base}<br />\n";
print "Charset: " . join("",$basex->charset) . "<br />\n";
print "Raw: $rand<br /><br />\n";
print "Encoded: $enc<br />\n";
print "Decoded: $dec<br />\n";

///////////////////////////////////////////////////////////////////////////
*/
class basex {

    public function __construct() {
        $this->min_digits = 5;
        $this->charset = array();
		$this->debug = false;
    }

    public function basex_encode($number) {
        $base = $this->base;
        $base || $base = sizeof($this->charset);
        $min_digits = $this->min_digits;

        $charset = $this->charset;
    
        if (!$number) { sprintf("%0{$min_digits}s",0); }
    	$ret = "";
		$count = 0;
        while ($number) {
            $digit = $number % $base;
            $ret = $charset[$digit] . $ret;
            $number = ($number - $digit) / $base;
    
            if ($this->debug) { print "$digit - "; }
    
            $count++;
    
            if ($count > 10) { exit; }
        }
    
        if ($this->debug) { print "<br />"; }
    
        $ret = sprintf("%0{$min_digits}s",$ret);
    
        return $ret;
    }
    
    public function basex_decode($string) {
		$base = $this->base;
        $base || $base = sizeof($this->charset);
        $min_digits = $this->min_digits;

        $charset = $this->charset;
    
        // Do this so it's easier to do a reverse lookup
		$count = 0;
        foreach ($charset as $item) {
            $info[$item] = intval($count);
            $count++;
        }
    	$ret = 0;
        for($i=0;$i<strlen($string);$i++) {
            $char = substr($string,$i,1);
            $val = $info[$char];
            $digit_pos = (strlen($string) - $i) - 1;
            $digit_val = $val * pow($base,$digit_pos);
    
            $ret += $digit_val;
            if ($this->debug) { print "$char => $val ($val * ($digit_pos^$base) = $digit_val)<br /> "; }
        }
    
        return $ret;
    }
}

?>
